package service

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"log"
	"net/http"
	"path"
	"strings"
	"weibo_1006/pkg"
)

func UploadFile(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")

	if file.Size > 2*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "图片大于2MB",
			"data":    "",
		})
		return
	}

	ect := strings.ToLower(path.Ext(file.Filename))
	if !strings.Contains(".jpg.png", ect) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "文件格式只能是,jpg/png",
			"data":    "",
		})
		return
	}

	file.Filename = uuid.NewString() + ".jpg"
	log.Println(file.Filename)

	url := "./files/" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, url)

	uploadFile := pkg.UploadFile(url)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "图片上传成功",
		"data":    uploadFile,
	})
}
